package abc.filter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RefreshScope
@Order(Ordered.HIGHEST_PRECEDENCE)
public class HeadersFilter implements WebFilter, GlobalFilter, Ordered {


    private volatile ThreadLocal<HttpHeaders> localFilterHeaders = new ThreadLocal<>();

    public HttpHeaders getHeaders() {
        return localFilterHeaders.get();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.info("HeadersFilter WebFilterChain doing......");
        return validationChain(exchange, chain);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("HeadersFilter GatewayFilterChain doing......");
        return validationChain(exchange, chain);
    }

    private Mono<Void> validationChain(ServerWebExchange exchange, Object chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        localFilterHeaders.set(headers);
        if(chain instanceof WebFilterChain) {
            return ((WebFilterChain) chain).filter(exchange);
        }
        else {
            return ((GatewayFilterChain) chain).filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
